package com.vms.control.weight.model;

import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

import com.vms.NetLog;

public class DateModel {

	private NetLog netLog = new NetLog("DateModel",true);
	private Collection<IOnDateChanged> mDateChangeListeners = new ArrayList<DateModel.IOnDateChanged>();
	private Calendar mCurrentUserDate = Calendar.getInstance();
	
	
	public interface IOnDateChanged {
		void onDateChanged ( Date date, boolean isToday );
	}

	public void setDate( Calendar newCalendar ){
		mCurrentUserDate = newCalendar;
	}

	public void setPrevDay() {
		mCurrentUserDate.add(Calendar.DATE, -1);
	}

	public void setNextDay() {
		mCurrentUserDate.add(Calendar.DATE, 1);		
	}

	public Date getDate() {
		return mCurrentUserDate.getTime();
	}
	
	
	/*
	 *  Listeners for Date update
	 */
	
	public void registerDateChangeListener(IOnDateChanged onDateChanged) {
		if( mDateChangeListeners.contains(onDateChanged) )
			return;
		
		mDateChangeListeners.add(onDateChanged);
	}
	
	public void removeDateChangeListener(IOnDateChanged onDateChanged) {
		if( mDateChangeListeners.contains(onDateChanged) )
			mDateChangeListeners.remove(onDateChanged);
	}
	
	public void removeAllDateChangeListener() {
			mDateChangeListeners.clear();
	}

	public void notifyListeners() {
		netLog.d("OnDateChanged [ listeners: "+mDateChangeListeners.size()+" ]");
		for (IOnDateChanged listener : mDateChangeListeners) {
			Date d = mCurrentUserDate.getTime();
			listener.onDateChanged(d,isToday(d));
		}
		
	}

	/*
	 * Static methods
	 */
	
	public static boolean isToday(Date d) {
		String todayStr = new SimpleDateFormat("yyyMMdd",Locale.US).format(new Date());
		String targetDayStr = new SimpleDateFormat("yyyMMdd",Locale.US).format(d);
		return todayStr.equals(targetDayStr);
	}
	
	public static CharSequence textDay(Date date, boolean isToday) {
		return new SimpleDateFormat("dd",Locale.US).format(date);
	}
	
	public static CharSequence textYear(Date date) {
		return new SimpleDateFormat("yyyy",Locale.US).format(date);
	}

	@SuppressWarnings("deprecation")
	public static CharSequence textMonth(Date date, boolean isToday) {
		return new DateFormatSymbols().getMonths()[date.getMonth()];
	}

}
